<!-- src/layouts/Header.vue -->
<template>
  <div class="header-container">
    <div class="left-section">
      <!-- 垂直布局 - 显示面包屑 -->
      <template v-if="appStore.settings.Layout === 'vertical'">
        <el-breadcrumb v-if="appStore.settings.ShowBreadcrumb" separator="/">
          <el-breadcrumb-item
            v-for="(item, index) in breadcrumbs"
            :key="index"
            :to="item.path ? { path: item.path } : undefined"
          >
            {{ item.title }}
          </el-breadcrumb-item>
        </el-breadcrumb>
      </template>

      <!-- 水平布局 - 显示 Logo 和菜单 -->
      <template v-else-if="appStore.settings.Layout === 'horizontal'">
        <div class="horizontal-header-left">
          <!-- Logo -->
          <div class="header-logo">
            <div class="logo-icon">
              <svg viewBox="0 0 24 24" fill="currentColor" class="logo-svg">
                <path d="M12 2L2 7v10c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V7l-10-5z"/>
              </svg>
            </div>
            <div class="logo-text">
              <span class="logo-title">{{ appStore.settings.Title }}</span>
            </div>
          </div>

          <!-- 横向菜单 -->
          <el-menu
            :default-active="activeMenu"
            mode="horizontal"
            router
            class="horizontal-menu"
          >
            <template v-for="route in menuRoutes" :key="route.path">
              <el-menu-item 
                v-if="!route.children || route.children.length === 0"
                :index="route.path"
              >
                <el-icon v-if="route.meta?.icon">
                  <component :is="getIconComponent(route.meta.icon)" />
                </el-icon>
                <span>{{ route.meta?.title }}</span>
              </el-menu-item>
              <el-sub-menu 
                v-else
                :index="route.path"
              >
                <template #title>
                  <el-icon v-if="route.meta?.icon">
                    <component :is="getIconComponent(route.meta.icon)" />
                  </el-icon>
                  <span>{{ route.meta?.title }}</span>
                </template>
                <el-menu-item
                  v-for="child in route.children"
                  :key="child.path"
                  :index="child.path"
                >
                  <el-icon v-if="child.meta?.icon">
                    <component :is="getIconComponent(child.meta.icon)" />
                  </el-icon>
                  <span>{{ child.meta?.title }}</span>
                </el-menu-item>
              </el-sub-menu>
            </template>
          </el-menu>
        </div>
      </template>

      <!-- 混合布局 - 显示面包屑 -->
      <template v-else>
        <el-breadcrumb v-if="appStore.settings.ShowBreadcrumb" separator="/">
          <el-breadcrumb-item
            v-for="(item, index) in breadcrumbs"
            :key="index"
            :to="item.path ? { path: item.path } : undefined"
          >
            {{ item.title }}
          </el-breadcrumb-item>
        </el-breadcrumb>
      </template>
    </div>

    <div class="right-section">
      <!-- 通知图标 -->
      <el-popover
        placement="bottom-end"
        :width="420"
        trigger="click"
        popper-class="notification-popover"
      >
        <template #reference>
          <div class="notification-icon">
            <el-badge :value="notificationCount" :hidden="notificationCount === 0" class="notification-badge">
              <el-icon class="icon-button">
                <Bell />
              </el-icon>
            </el-badge>
          </div>
        </template>
        
        <!-- 通知内容 -->
        <div class="notification-content">
          <div class="notification-header">
            <h3>通知</h3>
            <el-button type="text" size="small" @click="markAllAsRead">全部已读</el-button>
          </div>
          <div class="notification-list">
            <div 
              v-for="notification in notifications" 
              :key="notification.id"
              class="notification-item"
              :class="{ 'unread': !notification.read }"
              @click="markAsRead(notification.id)"
            >
              <div class="notification-icon-small">
                <el-icon>
                  <Bell v-if="notification.type === 'system'" />
                  <ChatDotRound v-else-if="notification.type === 'message'" />
                  <Warning v-else />
                </el-icon>
              </div>
              <div class="notification-content-text">
                <div class="notification-title">{{ notification.title }}</div>
                <div class="notification-desc">{{ notification.description }}</div>
                <div class="notification-time">{{ formatTime(notification.time) }}</div>
              </div>
              <div v-if="!notification.read" class="unread-dot"></div>
            </div>
            <div v-if="notifications.length === 0" class="empty-notifications">
              <el-icon class="empty-icon"><Bell /></el-icon>
              <p>暂无通知</p>
            </div>
          </div>
        </div>
      </el-popover>

      <!-- 消息图标 -->
      <div class="message-icon" @click="handleMessageClick">
        <el-badge :value="messageCount" :hidden="messageCount === 0" class="message-badge">
          <el-icon class="icon-button">
            <ChatDotRound />
          </el-icon>
        </el-badge>
      </div>

      <!-- 用户信息下拉菜单 -->
      <el-dropdown @command="handleCommand" trigger="click">
        <div class="user-info">
          <div class="avatar-wrapper">
            <el-avatar :size="32" :src="userStore.userInfo?.avatar" :icon="UserFilled" />
          </div>
          <div class="user-text">
            <span class="username">{{ userStore.userInfo?.nickname || userStore.userInfo?.username || '用户' }}</span>
          </div>
          <el-icon class="arrow-icon">
            <ArrowDown />
          </el-icon>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="profile">
              <el-icon><User /></el-icon>
              账户设置
            </el-dropdown-item>
            <el-dropdown-item command="logout">
              <el-icon><SwitchButton /></el-icon>
              退出系统
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <!-- 设置图标 -->
      <div class="settings-icon" @click="openSettings">
        <el-icon class="icon-button">
          <Setting />
        </el-icon>
      </div>
    </div>

    <!-- 设置抽屉 -->
    <SettingsDrawer ref="settingsDrawerRef" />
  </div>
</template>

<script setup>
import { computed, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  UserFilled,
  ArrowDown,
  User,
  SwitchButton,
  Bell,
  ChatDotRound,
  Warning,
  Setting,
} from "@element-plus/icons-vue";
import { useUserStore } from "@/store/user";
import { useAppStore } from "@/store/app";
import SettingsDrawer from "@/components/SettingsDrawer.vue";
import * as ElementPlusIconsVue from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const appStore = useAppStore();

// 获取激活的菜单
const activeMenu = computed(() => route.path);

// 获取菜单路由（用于水平布局）
const menuRoutes = computed(() => {
  const routes = router.getRoutes();
  const rootRoute = routes.find(r => r.path === '/');
  
  if (!rootRoute || !rootRoute.children) {
    return [];
  }
  
  // 过滤掉隐藏的菜单项
  return rootRoute.children.filter((child) => !child.meta?.hidden);
});

// 获取图标组件
const getIconComponent = (iconName) => {
  if (!iconName) return ElementPlusIconsVue.Document;
  // 将图标名转换为组件名（首字母大写，驼峰命名）
  const componentName = iconName
    .split('-')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join('');
  return ElementPlusIconsVue[componentName] || ElementPlusIconsVue.Document;
};

// 设置抽屉引用
const settingsDrawerRef = ref(null);

// 通知和消息数量
const notificationCount = ref(7);
const messageCount = ref(3);

// 通知数据
const notifications = ref([
  {
    id: 1,
    type: 'system',
    title: '系统更新通知',
    description: '系统将在今晚22:00进行维护更新，预计耗时2小时',
    time: new Date(Date.now() - 30 * 60 * 1000), // 30分钟前
    read: false
  },
  {
    id: 2,
    type: 'message',
    title: '新消息',
    description: '您有3条新的私信消息',
    time: new Date(Date.now() - 2 * 60 * 60 * 1000), // 2小时前
    read: false
  },
  {
    id: 3,
    type: 'warning',
    title: '安全提醒',
    description: '检测到异常登录，请及时检查账户安全',
    time: new Date(Date.now() - 4 * 60 * 60 * 1000), // 4小时前
    read: true
  },
  {
    id: 4,
    type: 'system',
    title: '功能更新',
    description: '新增了文件上传功能，欢迎体验',
    time: new Date(Date.now() - 24 * 60 * 60 * 1000), // 1天前
    read: true
  },
  {
    id: 5,
    type: 'message',
    title: '团队邀请',
    description: '您被邀请加入"产品设计团队"',
    time: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000), // 2天前
    read: true
  }
]);

// 面包屑导航
const breadcrumbs = computed(() => {
  const matched = route.matched.filter((item) => item.meta?.title);
  return matched.map((item) => ({
    path: item.path,
    title: item.meta?.title,
  }));
});

// 格式化时间
const formatTime = (time) => {
  const now = new Date();
  const diff = now - time;
  const minutes = Math.floor(diff / (1000 * 60));
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  
  if (minutes < 60) {
    return `${minutes}分钟前`;
  } else if (hours < 24) {
    return `${hours}小时前`;
  } else {
    return `${days}天前`;
  }
};

// 标记单个通知为已读
const markAsRead = (id) => {
  const notification = notifications.value.find(n => n.id === id);
  if (notification && !notification.read) {
    notification.read = true;
    updateNotificationCount();
  }
};

// 标记所有通知为已读
const markAllAsRead = () => {
  notifications.value.forEach(notification => {
    notification.read = true;
  });
  updateNotificationCount();
  ElMessage.success("已标记所有通知为已读");
};

// 更新通知数量
const updateNotificationCount = () => {
  notificationCount.value = notifications.value.filter(n => !n.read).length;
};

// 消息点击处理
const handleMessageClick = () => {
  ElMessage.info("消息功能待开发");
};

// 打开设置抽屉
const openSettings = () => {
  settingsDrawerRef.value?.open();
};

// 下拉菜单命令处理
const handleCommand = async (command) => {
  switch (command) {
    case "profile":
      ElMessage.info("账户设置功能待开发");
      break;
    case "logout":
      await handleLogout();
      break;
  }
};

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm("确定要退出登录吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    userStore.logout();
    ElMessage.success("已退出登录");
    router.push("/login");
  } catch (error) {
    // 用户取消
  }
};
</script>

<style scoped>
.header-container {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-section {
  display: flex;
  align-items: center;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 通知和消息图标样式 */
.notification-icon,
.message-icon {
  position: relative;
  cursor: pointer;
  padding: 8px;
  border-radius: 8px;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40px;
  width: 40px;
}

.notification-icon:hover,
.message-icon:hover {
  background: #f5f5f5;
}

.icon-button {
  font-size: 20px;
  color: #5f6368;
  transition: color 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.notification-icon:hover .icon-button,
.message-icon:hover .icon-button {
  color: #1a73e8;
}

/* Badge样式 */
:deep(.notification-badge .el-badge__content),
:deep(.message-badge .el-badge__content) {
  background: #ff4444;
  border: 2px solid #ffffff;
  font-size: 11px;
  font-weight: 600;
  min-width: 18px;
  height: 18px;
  line-height: 14px;
  padding: 0 4px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 4px 8px 4px 4px;
  border-radius: 20px;
  transition: all 0.2s ease;
  background: transparent;
  border: 1px solid transparent;
}

.user-info:hover {
  background: #f5f5f5;
}

.avatar-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-text {
  display: flex;
  flex-direction: column;
  gap: 0;
  min-width: 60px;
}

.username {
  font-size: 14px;
  color: #202124;
  font-weight: 500;
  line-height: 1.2;
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.arrow-icon {
  color: #5f6368;
  font-size: 14px;
  transition: transform 0.25s ease;
}

.user-info:hover .arrow-icon {
  color: #1a73e8;
  transform: translateY(1px);
}

:deep(.el-avatar) {
  border: 2px solid #ffffff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

:deep(.el-breadcrumb) {
  font-size: 14px;
}

:deep(.el-breadcrumb__item) {
  color: #606266;
}

:deep(.el-breadcrumb__item:last-child .el-breadcrumb__inner) {
  color: #303133;
  font-weight: 500;
}

:deep(.el-dropdown-menu) {
  padding: 6px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e8eaed;
  min-width: 140px;
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.2s ease;
  margin: 1px 0;
  font-size: 14px;
}

:deep(.el-dropdown-menu__item:hover) {
  background: #f5f5f5;
  color: #1a73e8;
}

:deep(.el-dropdown-menu__item .el-icon) {
  font-size: 16px;
  color: #5f6368;
}

:deep(.el-dropdown-menu__item:hover .el-icon) {
  color: #1a73e8;
}

:deep(.el-dropdown-menu__item--divided) {
  margin-top: 6px;
  border-top: 1px solid #e8eaed;
  padding-top: 8px;
}

/* 通知弹窗样式 */
.notification-content {
  max-height: 600px;
  overflow-y: auto;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 0 12px 0;
  border-bottom: 1px solid #e8eaed;
  margin-bottom: 8px;
}

.notification-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #202124;
}

.notification-list {
  max-height: 300px;
  overflow-y: auto;
}

.notification-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
  transition: background-color 0.2s ease;
  position: relative;
}

.notification-item:hover {
  background-color: #f8f9fa;
}

.notification-item.unread {
  background-color: #f0f8ff;
  border-left: 3px solid #1a73e8;
  padding-left: 8px;
}

.notification-icon-small {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  flex-shrink: 0;
}

.notification-icon-small .el-icon {
  font-size: 16px;
  color: #5f6368;
}

.notification-content-text {
  flex: 1;
  min-width: 0;
}

.notification-title {
  font-size: 14px;
  font-weight: 600;
  color: #202124;
  margin-bottom: 4px;
  line-height: 1.3;
}

.notification-desc {
  font-size: 13px;
  color: #5f6368;
  margin-bottom: 4px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.notification-time {
  font-size: 12px;
  color: #9aa0a6;
}

.unread-dot {
  width: 8px;
  height: 8px;
  background-color: #1a73e8;
  border-radius: 50%;
  position: absolute;
  top: 16px;
  right: 0;
}

.empty-notifications {
  text-align: center;
  padding: 40px 20px;
  color: #9aa0a6;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
  color: #e8eaed;
}

.empty-notifications p {
  margin: 0;
  font-size: 14px;
}

/* 通知弹窗全局样式 */
:deep(.notification-popover) {
  padding: 0 !important;
  border-radius: 8px !important;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1) !important;
  border: 1px solid #e8eaed !important;
}

:deep(.notification-popover .el-popover__content) {
  padding: 16px !important;
}

/* 设置图标 */
.settings-icon {
  cursor: pointer;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.settings-icon:hover {
  transform: rotate(90deg);
}

.settings-icon .icon-button {
  font-size: 20px;
  color: #5f6368;
  transition: color 0.3s ease;
}

.settings-icon:hover .icon-button {
  color: #409EFF;
}

/* 水平布局 - Header Left Section */
.horizontal-header-left {
  display: flex;
  align-items: center;
  gap: 24px;
  flex: 1;
}

.header-logo {
  display: flex;
  align-items: center;
  gap: 12px;
  padding-right: 24px;
  border-right: 1px solid #e8eaed;
}

.header-logo .logo-icon {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, var(--el-color-primary) 0%, var(--el-color-primary-dark-2) 100%);
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.header-logo .logo-svg {
  width: 20px;
  height: 20px;
  color: #ffffff;
}

.header-logo .logo-text {
  display: flex;
  flex-direction: column;
}

.header-logo .logo-title {
  font-size: 18px;
  font-weight: 600;
  color: #202124;
  letter-spacing: 0.3px;
  white-space: nowrap;
}

/* 水平菜单样式 */
.horizontal-menu {
  flex: 1;
  border: none;
  background: transparent;
}

.horizontal-menu :deep(.el-menu-item),
.horizontal-menu :deep(.el-sub-menu__title) {
  height: 64px;
  line-height: 64px;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
  padding: 0 20px;
}

.horizontal-menu :deep(.el-menu-item.is-active) {
  border-bottom-color: var(--el-color-primary);
  color: var(--el-color-primary);
  background: transparent;
}

.horizontal-menu :deep(.el-menu-item:hover),
.horizontal-menu :deep(.el-sub-menu__title:hover) {
  background: rgba(0, 0, 0, 0.04);
}

.horizontal-menu :deep(.el-sub-menu.is-active > .el-sub-menu__title) {
  border-bottom-color: var(--el-color-primary);
  color: var(--el-color-primary);
}

.horizontal-menu :deep(.el-icon) {
  margin-right: 6px;
}
</style>
